package com.xxx.service.impl;

import com.xxx.domain.MessageSms;
import com.xxx.service.IMessageSmsService;
import com.xxx.service.IVerifyCodeService;
import com.xxx.util.AssertUtil;
import com.xxx.util.StrUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private IMessageSmsService messageSmsService;

    // 发送短信验证码
    @Override
    public void sendSmsCode(String phone) {
        //校验手机号是否合法
        AssertUtil.isPhone(phone, "手机号格式不正确！");
        Date now = new Date();
        //判断该手机号是否已发送验证码(查看Redis中是否有缓存)
        String smsCodeKey = "smsreg:" + phone;
        String code = null;
        Object smsCode = redisTemplate.opsForValue().get(smsCodeKey);//获取Redis中缓存中对应的value值
        //生成验证码
        if (smsCode == null) {
            //利用工具类生成验证码
            code = StrUtils.getRandomString(6);
            String smsCodeValue = code + ':' + System.currentTimeMillis();
            //缓存验证码
            redisTemplate.opsForValue().set(smsCodeKey, smsCodeValue, 5, TimeUnit.MINUTES);
        } else {
            //把验证码及创建时间转成字符串
            String smsCodeValue = smsCode.toString();
            //判断验证码是否已过期
            String[] redisCodeValueArr = smsCodeValue.split(":");
            Long createTime = Long.parseLong(redisCodeValueArr[1]);//获取Redis中验证码创建时间
            //判断验证码是否已过期
            if (now.getTime() - createTime > 5 * 60 * 1000) {
                //redisTemplate.delete(smsCodeKey);
                //利用工具类生成验证码
                code = StrUtils.getRandomString(6);
                String smsCodeValue2 = code + ':' + System.currentTimeMillis();
                //缓存验证码
                redisTemplate.opsForValue().set(smsCodeKey, smsCodeValue2, 5, TimeUnit.MINUTES);
            } else {
                //判断缓存中是否有该手机号,如果有则不符合断言,返回提示信息message
                //如果Redis中已经存在该手机号的验证码记录（hasKey返回true），应该阻止重复发送
                AssertUtil.isTrue(smsCode == null, "该手机号已发送验证码，请耐心等待,请勿重复发送！");
            }
        }
        //调用发短信的接口,发短信(打印控制台)
        String content = "您的验证码是[" + code + "],请在5分钟内使用";
        System.out.println(content);
        //记录发送短信日志
        MessageSms messageSms = new MessageSms();
        messageSms.setTitle("用户注册短信");
        messageSms.setContent(content);
        messageSms.setSendTime(new Date(System.currentTimeMillis()));
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.getRequestAttributes();
        String ip = requestAttributes.getRequest().getRemoteAddr();
        messageSms.setIp(ip);
        messageSmsService.insert(messageSms);
    }

}